package com.weiwei.diancan.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.weiwei.diancan.Contant.ConfigMethod;
import com.weiwei.diancan.R;
import com.weiwei.diancan.adapter.OrderDetailAndAdapter;
import com.weiwei.diancan.adapter.SearchOrderAdapter;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.FindOrderBean;
import com.weiwei.diancan.bean.LoginBean;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.http.RetrofitFactory;
import com.weiwei.diancan.view.EmptyLayout;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import weiwei.com.weiweilibrary.adapter.BaseQuickAdapter;
import weiwei.com.weiweilibrary.views.ToastUtil;


/**
 * Created by BMW on 2016/11/7.
 */
public class SearchOrderActivity extends BaseActivity {
    private TextView tv_date_start;
    private TextView tv_date_end;
    private RecyclerView recycler;
    private SearchOrderAdapter adapter;
    private List<FindOrderBean.OrderListBean> value;
    private EmptyLayout emptyLayout;
    private TextView tv_search;
    private String start,end;

    @Override
    public void getData() {


    }

    @Override
    public void setListeners() {
        tv_date_start.setOnClickListener(v->initDate(tv_date_start));
        tv_date_end.setOnClickListener(v->initDate(tv_date_end));
        tv_search.setOnClickListener(v->getfind_order());

        adapter.setOnRecyclerViewItemClickListener(
                (view, position, data) -> {
                    FindOrderBean.OrderListBean orderListBean = (FindOrderBean.OrderListBean)data.get(position);
                    List<FindOrderBean.OrderListBean.LogListBean> log_list = orderListBean.getLog_list();
                    List<LoginBean.OrderListBean.LogListBean> login_log_list = new ArrayList<>();

                    for(FindOrderBean.OrderListBean.LogListBean logListBean:log_list){
                        LoginBean.OrderListBean.LogListBean login_logListBean = new LoginBean.OrderListBean.LogListBean();
                        login_logListBean.setLog_count(logListBean.getLog_count());
                        login_logListBean.setLog_id(logListBean.getLog_id());
                        login_logListBean.setLog_money(logListBean.getLog_money());
                        login_logListBean.setLog_name(logListBean.getLog_name());
                        login_logListBean.setLog_type(logListBean.getLog_type());
                        login_logListBean.setLog_unit(logListBean.getLog_unit());
                        login_logListBean.setLog_price(logListBean.getLog_price());

                        login_log_list.add(login_logListBean);
                    }

                    LoginBean.OrderListBean login = new LoginBean.OrderListBean();
                    login.setLog_list(login_log_list);
                    login.setOrder_id(orderListBean.getOrder_id());
                    login.setOrder_state(orderListBean.getOrder_state());
                    login.setOrder_type(orderListBean.getOrder_type());
                    login.setFather_id(orderListBean.getFather_id());
                    login.setOrder_no(orderListBean.getOrder_no());
                    login.setWaiter_id(orderListBean.getWaiter_id());
                    login.setOrder_person(orderListBean.getOrder_person());
                    login.setInsert_time(orderListBean.getInsert_time());

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data",login);
                    openActivity(OrderDetailAndActivity.class, bundle);
                });
    }

    @Override
    public void initView() {
        tv_date_start = (TextView)findViewById(R.id.tv_date_start);
        tv_date_end = (TextView)findViewById(R.id.tv_date_end);
        recycler = (RecyclerView)findViewById(R.id.recycler);
        emptyLayout = (EmptyLayout)findViewById(R.id.emptyLayout);
        tv_search = (TextView)findViewById(R.id.tv_search);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setHasFixedSize(true);

        tv_date_end.setText(end);
        tv_date_start.setText(start);

        adapter = new SearchOrderAdapter(value);
        recycler.setAdapter(adapter);

        if(value.size() == 0){
            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
        }else{
            emptyLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void initTitle() {
        titler.setText("查看订单");
        iv_left.setVisibility(View.VISIBLE);
        iv_left.setText("返回");
        iv_left.setOnClickListener(v->finish());
    }

    @Override
    public void setLayoutView() {
        setContentView(R.layout.activity_search_order);
        Intent intentGet = getIntent();
        value = (List<FindOrderBean.OrderListBean>) intentGet.getSerializableExtra("value");
        start = intentGet.getStringExtra("start");
        end = intentGet.getStringExtra("end");
        if(value == null){
            value = new ArrayList<>();
        }
    }

    public void initDate(TextView textView){
        Calendar c = Calendar.getInstance();
        String date = textView.getText().toString();

        int current_year = c.get(Calendar.YEAR);
        int current_month = c.get(Calendar.MONTH);
        int current_day = c.get(Calendar.DAY_OF_MONTH);

        if(!TextUtils.isEmpty(date)){
            String[] split = date.split("-");
            current_year = Integer.parseInt(split[0]);
            current_month = Integer.parseInt(split[1])-1;
            current_day = Integer.parseInt(split[2]);
        }
        new DatePickerDialog(this, (view, year, month, dayOfMonth) ->
            textView.setText(year+"-"+(month+1)+"-"+dayOfMonth),
                current_year,current_month,current_day).show();
    }

    /**
     *
     *  获取权限管理
     */
    private void getfind_order(){
        progressDialog.setMessage("数据获取中...");
        progressDialog.show();
        String start_date = tv_date_start.getText().toString().trim();
        String date_end = tv_date_end.getText().toString().trim();

        if(!checkDate(start_date.split("-"),date_end.split("-"),0)) {
            ToastUtil.showToast(this,"结束日期必须大于开始日期！");
            progressDialog.cancel();
            return;
        }

        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token, CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.date_start,start_date);
        map.put(ConfigMethod.date_end,date_end);

        RetrofitFactory.getIntance().find_order(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<FindOrderBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        ToastUtil.showToast(SearchOrderActivity.this,"网络连接异常");
                    }

                    @Override
                    public void onNext(FindOrderBean findOrderBean) {
                        progressDialog.cancel();
                        if(findOrderBean.getIs_success().equals("1")){
                            setViewData(findOrderBean);
                        }else if(findOrderBean.getIs_success().equals("-1")){
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }else if(findOrderBean.getIs_success().equals("-2")){
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }else{
                            ToastUtil.showToast(SearchOrderActivity.this,findOrderBean.getReason());
                        }
                    }
                });
    }

    /**
     * 设置界面数据
     */
    private void setViewData(FindOrderBean findOrderBean){
        value = findOrderBean.getOrder_list();
        if(value == null){
            value = new ArrayList<>();
        }
        if(value.size() == 0){
            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
        }else{
            emptyLayout.setVisibility(View.GONE);
        }
        adapter.setNewData(value);
    }

    /**
     * 日期检查
     * @return
     */
    private boolean checkDate(String start[],String end[],int i){
        int i1 = Integer.parseInt(start[i]);
        int i2 = Integer.parseInt(end[i]);

        if(i2 < i1) return false;
        else if(i2>i1) return true;
        else {
            if (i + 1 == start.length) return true;
            else return checkDate(start, end, ++i);
        }
    }
}
